package com.blb.ioc.myspring;

import java.lang.reflect.Field;

/**
 * 工厂模式，用于创建电脑对象
 */
public class ComputerFactory {

    /**
     * 获得电脑对象
     * @param clazz
     * @return
     */
    public Object getBean(Class clazz) throws IllegalAccessException, InstantiationException {
        //创建类的对象
        Object obj = clazz.newInstance();
        //获得类的所有属性
        Field[] fields = clazz.getDeclaredFields();
        for(Field field : fields) {
            //获得属性上配置的MyValue注解
            MyValue myValue = field.getDeclaredAnnotation(MyValue.class);
            //读取注解中的值
            if(myValue != null){
                String value = myValue.value();
                //给属性赋值
                field.setAccessible(true);
                field.set(obj,value);
            }
            //读取MyComponent注解
            MyComponent com = field.getDeclaredAnnotation(MyComponent.class);
            if(com != null){
                //读取配置的类型
                Class type = com.type();
                //创建组件的对象
                Object component = type.newInstance();
                //给组件赋值
                field.setAccessible(true);
                field.set(obj,component);
            }
        }
        return obj;
    }

    public static void main(String[] args) {
        ComputerFactory factory = new ComputerFactory();
        try {
            Computer computer = (Computer) factory.getBean(Computer.class);
            computer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
